import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Table,
  Modal,
  message,
  Slider,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import GoodsModal from './GoodsModal';
import { Link } from 'dva/router';
import styles from './style.less';
import G from '../../utils/g';
import moment from 'moment';

const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;
const {TextArea} = Input;


@connect(state => ({
  discount: state.discount,
}))
@Form.create()
export default class BasicForms extends PureComponent {
  state = {
    modalVisible: false,
    rowSelection: [],
    selectedGoods : [], //选中的商品列表
    detail : {
      rule : {
        limit : {}
      }
    }, //修改详情
  };

  componentDidMount() {
    const {dispatch, location} = this.props;
    this.id = G.getUrlValue('id', location.search);
    if (typeof this.id != 'undefined') {
      dispatch({
        type: 'discount/getDetail',
        payload: {
          id: this.id
        }
      }).then((res)=> {
        console.log(res);
        //this.setState(newState);

        this.setState({
          detail : res,
          selectedGoods : res.rangeList,
        });
      });
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    //this.props.form.resetFields();  //重置绑定表单数据
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return false;
      }
      //选中商品
      if(this.state.selectedGoods.length == 0){
        message.error('请选择促销商品');
        return false;
      }

      if(Array.isArray(values.time)){
        values.startTime = values.time[0].format('YYYY-MM-DD HH:mm:ss');
        values.endTime = values.time[1].format('YYYY-MM-DD HH:mm:ss');
      }
      delete values.time;

      /*

      {
   "type":0,
   "title":"直降1元",
   "startTime":"2018-05-22 12:00:00",
   "endTime":"2018-05-25 12:00:00",
   "tag":"惠买达人",
   "rule":{
      "limit":{
            "type":1, //0无限制 1限购
            "value":5 //限购数量
        },
      "rule":1.00  //直降金额或者折扣
    },
   "range":{
       spuId : ,
       value : 9,  //直降金额或者折扣
       type : 0,//直降或折扣
    }
   }

       */
      values.type = 0; //促销类型,目前只有限时折扣 0
      values.rule = {
        limit : {
                  type : Number(values.setting),  //0无限制 1限购
                  value : Number(values.number) || 0 //限购数量
                 },
      };
      console.log('this.state.selectedGoods',this.state.selectedGoods);
      values.range = this.state.selectedGoods.map(v=>{
        return {
          spuId : v.id,
          value : (values.discount ? (values.discount/10).toFixed(2) : '') || Number(values.reduce),  //直降金额或者折扣
          type : Number(values.discountType),  //0，直降，1折扣
        }
      });

      delete values.setting;
      delete values.number;
      delete values.discount;
      delete values.reduce;
      delete values.rangeType;

      if(this.id){values.id = this.id;}

      // values.success = ()=>{  //提交成功后的回调
      //   this.props.form.resetFields();  //重置绑定表单数据
      //   this.setState({
      //     selectedGoods : []
      //   });
      // };
      console.log(values);
      this.props.dispatch({
        type: 'discount/discountSave',
        payload: values,
      }).then(res=>{
        console.log(res);
        if(res && !this.id){  //新增才会清除表单,修改不需要
          this.props.form.resetFields();  //重置绑定表单数据
          this.setState({
            selectedGoods : []
          });
        }
      })
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });

  };

  changeSelectedGoods = (goods)=>{  //从弹框中获取到选中的商品
      console.log("goods", goods);
      let temp = [...this.state.selectedGoods];
      goods.forEach(v=>{
          console.log(v, 'includes',!temp.includes(v) );
          var include = false;
          temp.forEach(t=>{
              if(t.id == v.id){
                  include = true;
              }
          });
          if(!include){
              temp.push(v);
          }
      });
      this.setState({
          selectedGoods: temp
      });
  };

  removeSelected = (id)=>{  //移除选中的商品

    if(typeof id == 'undefined'){
      console.error('被移除的商品ID为空');
      return false;
    }
    let selectedGoods = [...this.state.selectedGoods];
    const result = selectedGoods.filter(v => v.id != id);
    //console.log('selectedGoods',selectedGoods, result);
    this.setState({
      selectedGoods : result
    });

  };

  render() {
    const id = this.id || '';
    const {modalVisible, selectedGoods, detail} = this.state;
    const {getFieldDecorator, getFieldValue,} = this.props.form;

    const type = getFieldValue('type') || detail.dType; //为了兼容修改初始化时商品折后价的计算
    const discount = getFieldValue('discount') || detail.dValue * 10;
    const reduce = getFieldValue('reduce') || detail.dValue;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const tableItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 17},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    return (
      <div>
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} style={{marginTop: 8}}>
            <FormItem {...formItemLayout} label="活动名称">
              {getFieldDecorator('title', {
                initialValue : detail.title,
                rules: [
                  {
                    required: true,
                    message: '请输入限时促销名称',
                  },
                ],
              })(<Input placeholder="请输入限时促销名称"/>)}
            </FormItem>
            <FormItem {...formItemLayout} label="有效时间">
              {getFieldDecorator('time', {
                initialValue : [moment(detail.startTime),moment(detail.endTime)],
                rules: [
                  {
                    required: true,
                    message: '请选择起止日期',
                  },
                ],
              })(<RangePicker style={{width: '100%'}} placeholder={['开始日期', '结束日期']} showTime />)}
            </FormItem>
            <FormItem {...formItemLayout} label="活动标签" help={`活动期间展示于商品详情的价格旁边，2至5字`}>
              {getFieldDecorator('tag', {
                initialValue : detail.tag,
                rules: [
                  {
                    required: true,
                    message: '请输入活动标签',
                  },
                  {
                    max : 5,
                    message: '最大不超过5个字',
                  },
                  {
                    min : 2,
                    message: '至少输入2个字',
                  }
                ],
              })(<Input placeholder="请输入活动标签"/>)}
            </FormItem>
            <FormItem {...formItemLayout} label="限购设置">
              <div>
                {getFieldDecorator('setting', {
                  initialValue: detail.rule.limit.type ? detail.rule.limit.type + "" : '0',
                })(
                  <Radio.Group>
                    <Radio value="0">不限购</Radio>
                    <Radio value="1">每人每种商品限X件</Radio>
                    <Radio value="2">每人每种商品前X件享受折扣</Radio>
                  </Radio.Group>
                )}
              </div>
            </FormItem>
            {
              getFieldValue('setting') != 0 ?
                <FormItem {...formItemLayout} label="限购件数">
                  {getFieldDecorator('number',{
                    initialValue : detail.rule.limit.value,
                    rules: [{
                      required: true,
                      message: '请输入限购件数',
                    }
                    ]
                  })(
                    <Select
                      mode="combobox"
                      placeholder="请输入限购件数"
                    >
                      <Option value="1">1</Option>
                      <Option value="2">2</Option>
                      <Option value="3">3</Option>
                      <Option value="4">4</Option>
                      <Option value="5">5</Option>
                      <Option value="10">10</Option>
                    </Select>
                  )}
                </FormItem>
              : null
            }

            <FormItem {...formItemLayout} label="折扣方式">
              <div>
                {getFieldDecorator('discountType', {
                  initialValue: detail.dType  ? (detail.dType + "") : "0",
                })(
                  <Radio.Group>
                    <Radio value="1">折扣方式</Radio>
                    <Radio value="0">降价方式</Radio>
                  </Radio.Group>
                )}

              </div>
            </FormItem>
            {
              getFieldValue('discountType') === '1' ?
              <FormItem label="折扣"  {...formItemLayout} help="请滑动设置折扣">
                  {getFieldDecorator('discount',{
                    initialValue: detail.dType == 1 ? (detail.dValue * 10) : 9,
                    rules: [
                      {
                        required: true,
                        message: '请输入折扣',
                      },
                    ],
                  })(

                    <Slider max={9.9} min={5} step={0.1} marks={{ 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10' }} />
                    )}
              </FormItem> :
              <FormItem label="降价金额" {...formItemLayout}>
                  {getFieldDecorator('reduce',{
                    initialValue : detail.dType == 0 ? detail.dValue : "",
                    rules: [
                      {
                        required: true,
                        message: '请输入降价金额',
                      },
                    ],
                  })(
                    <Input placeholder="请输入降价金额"/>
                  )}
              </FormItem>
            }

            {/*<FormItem {...formItemLayout} label="可使用商品">
              <div>
                {getFieldDecorator('rangeType', {
                  initialValue: '0',
                })(
                  <Radio.Group>
                    <Radio value="0">全部商品</Radio>
                    <Radio value="1">指定商品</Radio>
                  </Radio.Group>
                )}
              </div>
            </FormItem>*/}
            <FormItem {...tableItemLayout} label="促销商品" >
              <Button onClick={this.handleModalVisible}>请选择促销商品</Button>
              <Table
                style={{marginTop: '8px'}}
                pagination = {false}
                columns={[
                  {
                    title: '图片',
                    dataIndex: 'imgs',
                    render(val) {
                      return Array.isArray(val) ? <img src={`${val[0]}?imageView2/1/w/50`} width={50} /> : null;
                    },
                  },
                  {
                    title: '名称',
                    dataIndex: 'name',
                  },
                  {
                    title: '库存',
                    dataIndex: 'stock_count',
                    align: 'right',
                    render: val => `${val || 0}`,
                  },
                  {
                    title: '原价',
                    dataIndex: 'min_price',
                    align: 'right',
                    render: val => `${val || 0}元`,
                  },
                  {
                    title: '折后价',
                    align: 'right',
                    render: (val, record) => {
                      const price = record.min_price;
                      let result = price;
                      console.log('type为',type);
                      if(type == 1){  //折扣
                        if(discount){
                          result = (discount/10)*price;
                        }else{
                          result = price;
                        }
                      }else{ //直降
                        if(reduce){
                          result = price - reduce;
                        }else{
                          result = price;
                        }
                      }
                      return <span style={{color : '#ff5555'}}>{Number(result).toFixed(2)}元</span>
                    }
                  },
                  {
                    title: '操作',
                    render: (text,records)=> {
                      return <a onClick={()=>{this.removeSelected(records.id)}}>移除</a>
                    }
                  }
                ]}
                dataSource={selectedGoods}
                rowKey="id"
              ></Table>
            </FormItem>
            <FormItem {...submitFormLayout} style={{marginTop: 32}}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button style={{marginLeft: 8}}><Link to={`/sales/discount-list`}>返回</Link></Button>
            </FormItem>
          </Form>
        </Card>
        <GoodsModal
          type = "discount"
          dispatch={this.props.dispatch}
          modalVisible={modalVisible}
          handleHide={this.handleModalVisible}
          selectedRows = {selectedGoods}
          changeSelectedGoods = {this.changeSelectedGoods}
        />
      </div>
    );
  }
}
